import { getResultsAPI, getSuggestsAPI } from '@/api/search';
import { AppDispatch } from '@/store/index';
import { removeLocalHistories } from '@/utils/storage';
import { ActionType } from '../reducer/search';
export const getSuggestsAction = (keyword: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await getSuggestsAPI(keyword);
    dispatch({ type: 'search/saveSuggests', payload: res.data.options });
  };
};

export const clearSuggestsAction = (): ActionType => ({
  type: 'search/saveSuggests',
  payload: [],
});

export const savehistoriesAction = (histories: string[]): ActionType => ({
  type: 'search/saveHistories',
  payload: histories,
});

export const clearHistoriesAction = (): ActionType => {
  removeLocalHistories();
  return {
    type: 'search/clearHistories',
  };
};

export const getResultsAction = (q: string, page?: number) => {
  return async (dispatch: AppDispatch) => {
    const res = await getResultsAPI(q, page);
    dispatch({ type: 'search/saveResults', payload: res.data });
  };
};

export const clearResultsAction = (): ActionType => {
  return {
    type: 'search/clearResults',
  };
};
